package com.andaily.service.operation.job;

import com.andaily.domain.application.ApplicationInstance;
import com.andaily.domain.application.ApplicationInstanceRepository;
import com.andaily.domain.log.FrequencyMonitorLog;
import com.andaily.domain.log.reminder.PerMonitoringReminder;
import com.andaily.domain.shared.BeanProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 每一次的 心跳监测 执行类
 *
 * @author Shengzhao Li
 */
public class PerHeartBeatExecutor {

    private static final Logger LOGGER = LoggerFactory.getLogger(PerHeartBeatExecutor.class);

    private transient ApplicationInstanceRepository instanceRepository = BeanProvider.getBean(ApplicationInstanceRepository.class);
    private String instanceGuid;

    public PerHeartBeatExecutor(String instanceGuid) {
        this.instanceGuid = instanceGuid;
    }

    /**
     * Execute heart-beat
     * <p/>
     * 1.Send request and checking response
     * 2.Generate FrequencyMonitorLog
     * 3. If failed will notice
     * <p/>
     * <p/>
     * 执行心跳监测的流程
     * 1. 向指定的 URL 发送请求并检测响应情况
     * 2. 记录每一次的监控日志(FrequencyMonitorLog)
     * 3.若状态变更则发送提醒
     */
    public void execute() {
        final ApplicationInstance instance = instanceRepository.findByGuid(instanceGuid, ApplicationInstance.class);
        final FrequencyMonitorLog monitorLog = generateMonitorLog(instance);

        instanceRepository.saveOrUpdate(monitorLog);
        LOGGER.debug("Generate and persist FrequencyMonitorLog[{}]", monitorLog);
        //reminder
        remind(monitorLog);
    }

    /*
    * 处理 监控异常时的 提醒操作
    * */
    private void remind(FrequencyMonitorLog monitorLog) {
        PerMonitoringReminder reminder = new PerMonitoringReminder(monitorLog);
        reminder.remind();
    }

    /*
    * 生成 监控日志
    * */
    private FrequencyMonitorLog generateMonitorLog(ApplicationInstance instance) {
        FrequencyMonitorLogGenerator monitorLogGenerator = new FrequencyMonitorLogGenerator(instance);
        return monitorLogGenerator.generate();
    }
}